package com.itheima.service.cargo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.cargo.ExportDao;
import com.itheima.dao.cargo.PackingListDao;
import com.itheima.domain.cargo.*;
import com.itheima.service.cargo.PackingListService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

@Service
public class PackingListServiceImpl implements PackingListService {

    @Autowired
    private PackingListDao packingListDao;
    @Autowired
    private ExportDao exportDao;

    @Override
    public void deleteByPrimaryKey(String packingListId) {
        //先修改报运单的状态
        PackingList packingList = packingListDao.selectByPrimaryKey(packingListId);
        String[] split = packingList.getExportIds().split(",");
        for (String exportId : split) {
            Export export = new Export();
            export.setId(exportId);
            export.setState(2);
            exportDao.updateByPrimaryKeySelective(export);
        }
        //删除装箱单
        packingListDao.deleteByPrimaryKey(packingListId);
    }

    @Override
    public void insert(PackingList packingList, String[] exportIds) {
        //增加装箱单
        //需要查询下报运单的信息

        Integer totalCartons = 0;//总箱数
        Double totalVolume = 0.0;//总体积
        Double totalWeight = 0.0;//总重量
        for (int i = 0; i < exportIds.length; i++) {
            Export export = exportDao.selectByPrimaryKey(exportIds[i]);
            //export的箱数 总量  体积
            totalCartons += export.getBoxNums();//箱数
            totalVolume += export.getMeasurements();//体积
            totalWeight += export.getGrossWeights();//总重量
            //修改报运单状态  已装箱
            export.setState(3);
            exportDao.updateByPrimaryKeySelective(export);
        }
        packingList.setTotalCartons(totalCartons);
        packingList.setTotalVolume(totalVolume);
        packingList.setTotalWeight(totalWeight);
        packingListDao.insert(packingList);
    }

    @Override
    public List<PackingList> selectByExample(PackingListExample example) {
        return null;
    }

    @Override
    public PackingList selectByPrimaryKey(String packingListId) {
        return packingListDao.selectByPrimaryKey(packingListId);
    }

    @Override
    public void updateByPrimaryKeySelective(PackingList packingList) {
        //编辑装箱单
        packingListDao.updateByPrimaryKeySelective(packingList);
    }

    @Override
    public void updateByPrimaryKey(PackingList record) {

    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, PackingListExample packingListExample) {

        PageHelper.startPage(pageNum, pageSize);
        List<PackingList> list = packingListDao.selectByExample(packingListExample);

        return new PageInfo(list);
    }


}
